import { dialog, BrowserWindow } from 'electron'
import { autoUpdater } from 'electron-updater'
import log from 'electron-log'
// axios 需要通过require 引入
import axios from 'axios'
autoUpdater.autoDownload = false
let win = BrowserWindow.getFocusedWindow()
log.transports.file.level = 'debug'
autoUpdater.logger = log

autoUpdater.on('error', error => {
  // dialog.showErrorBox('Error: ', error == null ? 'unknown' : (error.stack || error).toString());
})

autoUpdater.on('update-available', info => {
  dialog
    .showMessageBox({
      type: 'info',
      title: '更新提示',
      message: '发现有新版本' + info.version + '，是否更新？',
      buttons: ['更新', '不了'],
      cancelId: 1
    })
    .then(index => {
      if (index.response == 0) {
        autoUpdater.downloadUpdate()
      }
    })
})

autoUpdater.on('update-not-available', () => {
  // dialog.showMessageBox({
  //   title: '提示',
  //   message: '暂无更新'
  // });
})

autoUpdater.on('update-downloaded', () => {
  dialog
    .showMessageBox({
      type: 'info',
      title: '安装更新',
      buttons: ['安装', '稍后安装'],
      message: '安装包已经下载完毕，是否现在安装？',
      cancelId: 1
    })
    .then(index => {
      if (index.response == 0) {
        autoUpdater.quitAndInstall(true, true)
      }
    })
})

autoUpdater.on('download-progress', function (progressObj) {
  win?.setProgressBar((progressObj.percent as any).toFixed(2) / 100)
})
// export this to MenuItem click callback
export async function checkForUpdates() {
  let name = await axios.get('https://gitee.com/api/v5/repos/fei-yuhao/markdown-k/tags').then((res: { data: { name: any }[] }) => {
    return res.data[0].name
  })

  autoUpdater.setFeedURL({
    provider: 'generic',
    url: `https://gitee.com/fei-yuhao/markdown-k/releases/download/${name}/`
  })
  autoUpdater.checkForUpdates()
}
